package de.eventdroid.helper_classes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.test.IsolatedContext;
import android.util.Log;

public class RESTHandler {

	/**
	 * Base path for the requests to the webservice
	 */
	private static final String URI_BASE_PATH = "http://www.redphoenix.de/eventdroid/recess/eventdroid/";
	private static String mockLocationCreateJSON = "{\"locationHandler\":{\"location_name\":\"Aachen Stadt\",\"location_description\":null,\"location_foto_link\":null,\"location_adress\":\"Kaiserplatz\",\"location_zip\":\"52080\",\"location_town\":\"Aachen\",\"location_latitude\":null,\"location_longitude\":null,\"location_telefone\":null,\"location_fax\":null,\"location_email\":null,\"location_website\":null,\"location_creator_user_id\":\"redphoenix\"}}";
	private static String mockUserCreateJSON = "{\"locationHandler\":{\"location_name\":\"Aachen Stadt\",\"location_description\":null,\"location_foto_link\":null,\"location_adress\":\"Kaiserplatz\",\"location_zip\":\"52080\",\"location_town\":\"Aachen\",\"location_latitude\":null,\"location_longitude\":null,\"location_telefone\":null,\"location_fax\":null,\"location_email\":null,\"location_website\":null,\"location_creator_user_id\":\"redphoenix\"}}";
	
	/**
	 * Fetchs the Ressources with the given URI from the server in JSON Data Format 
	 * @param ressourceURI Ressource Locator
	 * @return found Ressources in String format
	 */
 	public static String getData (String ressourceURI) {
		
		/**
	     * Fetch results of matching Events
	     */
		InputStream inputStream = null;
		StringBuilder aktStringBuilder = null;
		String resultString = "";
		
		/* http-get - get Data from the RESTful Server */
		try{			
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpGet request = new HttpGet(new URI(URI_BASE_PATH + ressourceURI));
		    
		    Log.w("STRING ",URI_BASE_PATH + ressourceURI);
		    
		    request.setHeader("User-Agent", "Mozilla/5.0(Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91)");
		    request.addHeader("accept", "application/json");
		    
		    HttpResponse response = httpclient.execute(request);
            
            Log.i("HTTP Request Status Code", response.getStatusLine().toString());
            
		    HttpEntity entity = response.getEntity();			    
		    inputStream = entity.getContent();
			
		} catch(Exception e) {
		    Log.e("HTTP Error", "Error in http connection: "+e.toString());
		}
	    
	    /* Convert the Response Content into a String */
	    try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf8"),8);
		    aktStringBuilder = new StringBuilder();
		    String line="empty";
		    while ((line = reader.readLine()) != null) {
		    	aktStringBuilder.append(line);
		    }
		    inputStream.close();
		    resultString = aktStringBuilder.toString();		    
		    
		    /* Cleanup Resultstring */
		    resultString = TextHandler.replaceUmlauts(resultString, "utf");
		    
		} catch(Exception e) {
			Log.e("Convert Error", "Error converting result "+e.toString());
		}
		
		return resultString;
	}

	/**
	 * 
	 * @param uriPath the path of the URI which defines the controller which handles the request
	 * @param postData the Data from which the new Ressource is created
	 * @return String with the 
	 */
	public static String postData(String uriPath, JSONObject postData) {
		
	    HttpClient httpclient = new DefaultHttpClient();
	    
	    HttpPost httppost = new HttpPost(URI_BASE_PATH+uriPath);
	    String responseCode = "";
	    
	    Log.e("POSTDATA", postData.toString());
	    
	    try {
	    	
	    	/* Building basic structure of POST request */
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            httppost.setHeader("User-Agent", "Mozilla/5.0(Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91)");
            //httppost.setHeader("Expect", "100-continue");  
            
            /* Adding parameters for creating the Ressource */
            List<NameValuePair> postParams = new ArrayList<NameValuePair>();
            postParams.add(new BasicNameValuePair("ressourceJsonData", postData.toString()));
            httppost.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));        
            
            /* Execute the HTTP Post request */
	        HttpResponse response = httpclient.execute(httppost);
	        responseCode = response.getStatusLine().toString();

		    /* Fetch delivered Data from Web Service */
			InputStream inputStream = null;
			StringBuilder aktStringBuilder = null;
			String resultString = "";
			
			/* http-get - get Data from the RESTful Server */
			try {			
			    HttpEntity httpEntity = response.getEntity();			    
			    inputStream = httpEntity.getContent();
			} catch(Exception e) {
			    Log.e("HTTP Error", "Error in http connection: "+e.toString());
			}
		    
		    /* Convert the Response Content into a String */
		    try{
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf8"),8);
			    aktStringBuilder = new StringBuilder();
			    String line="empty";
			    while ((line = reader.readLine()) != null) {
			    	aktStringBuilder.append(line);
			    }
			    inputStream.close();
			    resultString = aktStringBuilder.toString();		    
			    
			    /* Cleanup Resultstring */
			    resultString = TextHandler.replaceUmlauts(resultString, "html");
			    
			    Log.e("RESPONSE: ", resultString);
			    
			    Log.i("Result Content", resultString);
			} catch(Exception e) {
				Log.e("Convert Error", "Error converting result "+e.toString());
			}	    	
	        
	    } catch (Exception e) {
	    	Log.e("Kein Plan was anderes", "PROBLEM UNDEFINIERT: "+e);
	    }  
	    
	    return responseCode;
	    
	}
	
	/**
	 * This method updates existing location Ressources
	 * 
	 * @param uriPath The path which is added to the basepath to set the REST parameters for the Web Service
	 * @param putData The data which has to be updated
	 * @return The statuscode the server delivers
	 */	
	public static String putData(String uriPath, JSONObject putData) {
		 	
		HttpClient httpclient = new DefaultHttpClient();
		    
	    HttpPost httppost = new HttpPost(URI_BASE_PATH+uriPath);
	    
	    String responseCode = "";
	    
	    try {
	    	
	    	/* Building basic structure of POST request */
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            httppost.setHeader("User-Agent", "Mozilla/5.0(Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91)");
            //httppost.setHeader("Expect", "100-continue");  
            
            /* Adding parameters for creating the Ressource */
            List<NameValuePair> postParams = new ArrayList<NameValuePair>();
            postParams.add(new BasicNameValuePair("ressourceJsonData", putData.toString()));
            httppost.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));        
            
            /* Execute the HTTP Post request */
	        HttpResponse response = httpclient.execute(httppost);
	        responseCode = response.getStatusLine().toString();
	        
		    /* Fetch delivered Data from Web Service */
			InputStream inputStream = null;
			StringBuilder aktStringBuilder = null;
			String resultString = "";
			
			/* http-get - get Data from the RESTful Server */
			try {			
			    HttpEntity httpEntity = response.getEntity();			    
			    inputStream = httpEntity.getContent();
			} catch(Exception e) {
			    Log.e("HTTP Error", "Error in http connection: "+e.toString());
			}
		    
		    /* Convert the Response Content into a String */
		    try{
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf8"),8);
			    aktStringBuilder = new StringBuilder();
			    String line="empty";
			    while ((line = reader.readLine()) != null) {
			    	aktStringBuilder.append(line);
			    }
			    inputStream.close();
			    resultString = aktStringBuilder.toString();		    
			    
			    /* Cleanup Resultstring */
			    resultString = TextHandler.replaceUmlauts(resultString, "html");
			  
			} catch(Exception e) {
				Log.e("Convert Error", "Error converting result "+e.toString());
			}	    	
	        
	    } catch (Exception e) {
	    	Log.e("Kein Plan was anderes", "PROBLEM UNDEFINIERT: "+e);
	    }  
	    
	    return responseCode;
	}
	
	/**
	 * Deletes ressources with the uriPath given ressource
	 * @param uriPath URI path to the ressource which has to be deleted
	 * @return Statuscode if deleting succeeded
	 */
	public static String deleteData(String uriPath) {
		
		HttpClient httpclient = new DefaultHttpClient();
	    
	    HttpDelete httpdelete = new HttpDelete(URI_BASE_PATH+uriPath);
	    String responseCode = "";
	    
	    try {
	    	
	    	/* Building basic structure of POST request */
	    	httpdelete.setHeader("Accept", "application/json");
	    	httpdelete.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
	    	httpdelete.setHeader("User-Agent", "Mozilla/5.0(Linux; U; Android 2.2; en-gb; LG-P500 Build/FRF91)");
	    	//httpdelete.setHeader("Expect", "100-continue");  

            /* Execute the HTTP Post request */
	        HttpResponse response = httpclient.execute(httpdelete);
	        responseCode = response.getStatusLine().toString();

		    /* Fetch delivered Data from Web Service */
			InputStream inputStream = null;
			StringBuilder aktStringBuilder = null;
			String resultString = "";
			
			/* http-get - get Data from the RESTful Server */
			try {			
			    HttpEntity httpEntity = response.getEntity();			    
			    inputStream = httpEntity.getContent();
			} catch(Exception e) {
			    Log.e("HTTP Error", "Error in http connection: "+e.toString());
			}
		    
		    /* Convert the Response Content into a String */
		    try{
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf8"),8);
			    aktStringBuilder = new StringBuilder();
			    String line="empty";
			    while ((line = reader.readLine()) != null) {
			    	aktStringBuilder.append(line);
			    }
			    inputStream.close();
			    resultString = aktStringBuilder.toString();		    
			    
			    /* Cleanup Resultstring */
			    resultString = TextHandler.replaceUmlauts(resultString, "html");
			    
			    Log.i("Result Content", resultString);
			} catch(Exception e) {
				Log.e("Convert Error", "Error converting result "+e.toString());
			}	    	
	        
	    } catch (Exception e) {
	    	Log.e("Kein Plan was anderes", "PROBLEM UNDEFINIERT: "+e);
	    }  
	    
	    return responseCode;
	    
	}
	
}
